const express = require("express")
const fs = require("fs")

// https://github.com/nodejs/node-v0.x-archive/blob/master/lib/module.js

let cleanCache = require('./util/cleanCache.js')
let router = require("./routers/index.js")

let app = express()

app.use(function(req, res, next) {
  // 利用闭包的特性获取最新的router对象，避免app.use缓存router对象
  router(req, res, next)
})

app.listen(3000, _ => {
  console.log('服务启动： http://127.0.0.1:3000');
})

// 监听文件修改重新加载代码
fs.watch(require.resolve("./routers/index.js"), function() {
  cleanCache(require.resolve("./routers/index.js"))
  try {
    router = require("./routers/index.js")
  } catch (err) {
    console.error("module update failed")
  }
})


// http://fex.baidu.com/blog/2015/05/nodejs-hot-swapping/     抄袭来源